package de.stalinski.login;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class SessionWatcher {

    private static SessionWatcher SessionWatcher = null;
    private HashMap<String, String> users = new HashMap();
    private HashMap<String, Long> sessionTimeOut = new HashMap();
    private long minutes = 30;
    private long interval = 1000 * 60 * minutes;

    private SessionWatcher() {
    }

    public static SessionWatcher instance() {
        if (SessionWatcher == null) {
            SessionWatcher = new SessionWatcher();
        }
        return SessionWatcher;
    }

    public void register(String user, String id) {
        if (users.get(id) == null) {
            System.out.println("Register: " + user + "|" + id);
            users.put(id, user);
            sessionTimeOut.put(id, getSessionTimeOut());
        }
    }

    public void unregister(String user, String id) {
        if (users.get(id) != null) {
            System.out.println("Unregister: " + user + "|" + id);
            users.remove(id);
            sessionTimeOut.remove(id);
        }
    }

    public boolean isInList(String id) {
        return users.get(id) != null;
    }

    public void updateTimeOut(String id) {
        if (users.get(id) != null && sessionTimeOut.get(id) != null) {
            System.out.println("Old: " + sessionTimeOut.get(id));
            long newT = (1000 * 60) + sessionTimeOut.get(id);
            System.out.println("New: " + newT);
            sessionTimeOut.put(id, newT);
        }
    }

    public String getLogoutTime(String id) {
        Date time = null;
       
            time = new Date(sessionTimeOut.get(id));
       
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        return df.format(time);
    }

    private long getSessionTimeOut() {
        return System.currentTimeMillis() + interval;
    }

    public boolean timedOut(String id) {
        return (System.currentTimeMillis() > sessionTimeOut.get(id));
    }
}
